<template>
  <view class="table-container">
    <view class="table-header">
      <text class="table-title">仪器使用费表</text>
    </view>
    <view class="table-wrapper">
      <table class="data-table">
        <thead>
          <tr>
            <th>序号</th>
            <th>定额编号</th>
            <th>定额名称</th>
            <th>单位</th>
            <th>数量</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in list" :key="index" 
              @click="handleRowClick(index)" 
              @dblclick="handleRowDoubleClick(item, index)"
              :class="{ 
                'selected-row': selectedIndices.has(index),
                'modified-row': isRowModified(item)
              }">
            <td style="width: 5%;">{{ index + 1 }}</td>
            <td style="width: 16%;">{{ item.de_id }}</td>
            <td style="width: 24%;">{{ item.de_name }}</td>
            <td style="width: 10%;">{{ item.unit }}</td>
            <td style="width: 10%;">{{ item.count }}</td>
          </tr>
        </tbody>
      </table>
    </view>
  </view>
</template>

<script setup>
import { defineProps, defineEmits, ref, watch, onMounted, onUnmounted } from 'vue';

const props = defineProps({
  list: {
    type: Array,
    default: () => []
  },
  pendingChanges: {
    type: Array,
    default: () => []
  },
  modifiedRecords: {
    type: Array,
    default: () => []
  }
});

const emit = defineEmits(['row-double-click', 'project-changed', 'site-changed']);

const selectedIndices = ref(new Set());
const lastProjectId = ref(null);
const lastSiteId = ref(null);

// 当传入的 list 变化时，清空选中状态
watch(
  () => props.list,
  () => {
    selectedIndices.value.clear();
  }
);

// 组件挂载时初始化项目监听
onMounted(() => {
  initProjectWatch();
});

// 初始化项目和站点变化监听
function initProjectWatch() {
  // 获取初始项目ID和站点ID
  if (typeof window !== 'undefined') {
    if (window.currentProjectId) {
      lastProjectId.value = window.currentProjectId;
      console.log('仪器使用费-初始项目ID:', window.currentProjectId);
    }
    if (window.currentSiteId) {
      lastSiteId.value = window.currentSiteId;
      console.log('仪器使用费-初始站点ID:', window.currentSiteId);
    }
  }
  
  // 监听项目和站点变化
  const checkChanges = setInterval(() => {
    if (typeof window !== 'undefined') {
      // 检查项目变化
      const currentProjectId = window.currentProjectId;
      if (currentProjectId !== lastProjectId.value) {
        lastProjectId.value = currentProjectId;
        console.log('仪器使用费-项目已切换到:', currentProjectId);
        selectedIndices.value.clear();
        emit('project-changed', currentProjectId);
      }
      
      // 检查站点变化
      const currentSiteId = window.currentSiteId;
      if (currentSiteId !== lastSiteId.value) {
        lastSiteId.value = currentSiteId;
        console.log('仪器使用费-站点已切换到:', currentSiteId);
        selectedIndices.value.clear();
        emit('site-changed', currentSiteId);
      }
    }
  }, 500); // 每500ms检查一次
  
  // 组件卸载时清理定时器
  onUnmounted(() => {
    clearInterval(checkChanges);
  });
}

function handleRowClick(index) {
  console.log("仪器使用费-当前项目ID:", window.currentProjectId);
  console.log("仪器使用费-当前站点ID:", window.currentSiteId);
  if (selectedIndices.value.has(index)) {
    selectedIndices.value.delete(index);
  } else {
    selectedIndices.value.add(index);
  }
}

function handleRowDoubleClick(item, rowIndex) {
  emit('row-double-click', item, 'instrument', rowIndex);
}

// 检查行是否已被修改（暂存）
function isRowModified(item) {
  // 首先检查全局暂存记录
  if (typeof window !== 'undefined') {
    // 确保必要的全局变量存在
    if (!window.currentProjectId || !window.currentSiteId) {
      console.warn('项目ID或站点ID为空，无法检查暂存记录');
      return false;
    }
    
    // 初始化存储对象（如果不存在）
    if (!window.recordUpdateStorage) {
      window.recordUpdateStorage = {};
    }
    
    const recordKey = `${window.currentProjectId}_${window.currentSiteId}_${item.id}_instrument`;
    console.log('=== 仪器使用费暂存检查 ===');
    console.log('生成的Key:', recordKey);
    console.log('暂存记录存在:', !!window.recordUpdateStorage[recordKey]);
    
    if (window.recordUpdateStorage[recordKey]) {
      console.log('✅ 仪器使用费找到暂存记录，应该显示绿色高亮');
      return true;
    }
  }
  
  // 检查已提交的修改记录
  if (props.modifiedRecords && props.modifiedRecords.length > 0) {
    const itemId = item.id || item.de_id || item.ID || item.De_id;
    if (itemId && window.currentProjectId && window.currentSiteId) {
      // 使用与 classic.vue 中相同的格式
      const recordKey = `${window.currentProjectId}_${window.currentSiteId}_${itemId}_instrument`;
      console.log('=== 仪器使用费已修改记录检查 ===');
      console.log('生成的recordKey:', recordKey);
      console.log('modifiedRecords列表:', props.modifiedRecords);
      console.log('是否匹配:', props.modifiedRecords.includes(recordKey));
      
      if (props.modifiedRecords.includes(recordKey)) {
        return true;
      }
    }
  }
  
  // 然后检查 pendingChanges
  if (props.pendingChanges && props.pendingChanges.length > 0) {
    const itemId = item.id || item.de_id || item.ID || item.De_id;
    const hasPendingChange = props.pendingChanges.some(change => 
      String(change.originalRecordId) === String(itemId) && 
      change.type === 'instrument'
    );
    
    if (hasPendingChange) {
      console.log('✅ 仪器使用费找到pendingChanges记录，应该显示绿色高亮');
      return true;
    }
  }
  
  return false;
}
</script>

<style scoped>
.table-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  margin-bottom: 20px;
  overflow: hidden;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.table-wrapper {
  overflow: hidden;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
  table-layout: fixed;
}

.data-table th,
.data-table td {
  padding: 8px 4px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 设置各列的百分比宽度，自适应屏幕 */
.data-table th:nth-child(1),
.data-table td:nth-child(1) {
  width: 12%;
  text-align: center;
  white-space: nowrap;
}

.data-table th:nth-child(2),
.data-table td:nth-child(2) {
  width: 20%;
  white-space: nowrap;
}

.data-table th:nth-child(3),
.data-table td:nth-child(3) {
  width: 40%;
  white-space: normal;
  word-wrap: break-word;
  line-height: 1.3;
}

.data-table th:nth-child(4),
.data-table td:nth-child(4) {
  width: 14%;
  text-align: center;
  white-space: nowrap;
}

.data-table th:nth-child(5),
.data-table td:nth-child(5) {
  width: 14%;
  text-align: center;
  white-space: nowrap;
}

.data-table th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #333;
  position: sticky;
  top: 0;
  z-index: 10;
}

.data-table tbody tr:hover {
  background-color: #f5f7fa;
}

.data-table tbody tr {
  cursor: pointer;
}

.selected-row {
  background-color: #1e3a8a !important;
  color: #fff;
}

.selected-row td {
  color: #fff;
}

/* 已修改行的绿色高亮 */
.modified-row {
  background-color: #f0f9ff !important;
  border: 2px solid #67c23a;
  animation: modifiedHighlight 1s ease-in-out;
}

.modified-row td {
  color: #67c23a;
  font-weight: 600;
}

@keyframes modifiedHighlight {
  0% {
    background-color: #fff;
    border-color: transparent;
  }
  50% {
    background-color: #e8f5e8;
    border-color: #67c23a;
  }
  100% {
    background-color: #f0f9ff;
    border-color: #67c23a;
  }
}

/* 当行既被选中又被修改时的样式优先级 */
.selected-row.modified-row {
  background-color: #67c23a !important;
  border-color: #67c23a;
}

.selected-row.modified-row td {
  color: #fff !important;
}
</style>